package com.example.tvwanandroid.base

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.annotation.LayoutRes
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import butterknife.ButterKnife
import butterknife.Unbinder
import com.example.tvwanandroid.dialog.LoadingDialog

/**
 * @作者: njb
 * @时间: 2020/12/3 17:33
 * @描述:
 */
abstract class BaseActivity<P : BasePresenter<*>> : AppCompatActivity(), BaseView {
    lateinit var context: Context
    protected var presenter: P? = null
    protected var unbinder: Unbinder? = null

    private var waitDialog: LoadingDialog? = null

    protected abstract val layoutId: Int

    protected abstract fun createPresenter(): P

    protected abstract fun initView()

    protected abstract fun addListener()


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (layoutId != 0) {
            setContentView(layoutId)
        }
        unbinder = ButterKnife.bind(this)
        context = this
        presenter = createPresenter()
        initView()
        addListener()
    }


    /**
     * 打开Activity
     *
     * @param cls
     */
    fun startA(cls: Class<*>) {
        val intent = Intent(context, cls)
        startActivity(intent)
    }

    public override fun onPause() {
        super.onPause()
    }

    override fun onDestroy() {
        super.onDestroy()
        presenter!!.detachView()
        unbinder!!.unbind()
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            android.R.id.home -> {
                onBackPressed()
            }
        }
        return super.onOptionsItemSelected(item)
    }

    override fun onBackPressed() {
        super.onBackPressed()
        // Fragment 逐个出栈
        val count = supportFragmentManager.backStackEntryCount
        if (count == 0) {
            super.onBackPressed()
        } else {
            supportFragmentManager.popBackStack()
        }
    }


    /**
     * @param s
     */
    fun showtoast(s: String) {
        Toast.makeText(context, s, Toast.LENGTH_SHORT).show()
    }

    fun showFileDialog() {}

    fun hideFileDialog() {}

    /**
     * 显示加载框
     *
     * @param textRes
     * @param color
     */
    fun showWaitDialog(textRes: String, color: Int) {
        if (null == waitDialog) {
            waitDialog = LoadingDialog(this, textRes, color)
        } else {
            waitDialog!!.setShowText(textRes)
            if (!waitDialog!!.isShown) {
                waitDialog!!.showUp()
            }
        }
    }

    /**
     * 显示加载框
     */
    fun showWaitDialog() {
        if (null == waitDialog) {
            waitDialog = LoadingDialog(this)
        } else {
            waitDialog!!.setShowText("")
            if (!waitDialog!!.isShown) {
                waitDialog!!.showUp()
            }
        }
    }

    /**
     * 显示progressBar
     *
     * @param textRes 需要提示的字
     */
    fun showWaitDialog(textRes: Int) {
        if (null == waitDialog) {
            waitDialog = LoadingDialog(this, textRes)
        } else {
            waitDialog!!.setShowText(textRes)
            if (!waitDialog!!.isShown) {
                waitDialog!!.showUp()
            }
        }
    }

    /**
     * 销毁progressBar
     */
    fun dismissWaitDialog() {
        if (null != waitDialog && waitDialog!!.isShown) {
            waitDialog!!.dismiss()
        }
    }


    /**
     * 通过资源res获得view
     *
     * @param res
     * @return
     */
    fun getViewByRes(@LayoutRes res: Int): View {
        return LayoutInflater.from(context).inflate(res, null)
    }

    /**
     * 获得TextView 的文本
     *
     * @param tv
     * @return
     */
    fun getTV(tv: TextView?): String {
        return tv?.text?.toString()?.trim { it <= ' ' } ?: ""
    }

    override fun showError(msg: String) {
        showtoast(msg)
    }

    override fun onErrorCode(model: BaseResult<Any>) {
        when {
            model.errorCode < 0.toString() -> showtoast(model.errorMsg)
        }
    }

    override fun showLoadingFileDialog() {
        showWaitDialog()
    }

    override fun hideLoadingFileDialog() {
        dismissWaitDialog()
    }

    override fun onProgress(totalSize: Long, downSize: Long) {}

    fun addFragmentToActivity(
        fragmentManager: FragmentManager,
        fragment: Fragment, frameId: Int
    ) {
        val transaction = fragmentManager.beginTransaction()
        if (!fragment.isAdded)
            transaction.add(frameId, fragment)
        fragmentManager.fragments.filter { it.id == fragment.id }.map { transaction.hide(it) }
        transaction.show(fragment)
        transaction.commit()
    }
}